package com.focusai.efairy.ui.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.focusai.efairy.model.request.GetQiniuTokenRequest;
import com.focusai.efairy.model.response.QiniuTokenResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.Ipresenter.IUpLoadFilePresenter;
import com.focusai.efairy.ui.iview.IUpLoadFileListView;
import com.focusai.efairy.ui.iview.IUpLoadFileView;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.FileUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/8/19.
 */

public class UpLoadFilePresenter implements IUpLoadFilePresenter {

    private UploadManager uploadManager;

    public UpLoadFilePresenter() {
        this.uploadManager = new UploadManager();
    }

    private int upLoadFilecount = 0;
    private LinkedHashMap<String, String> urlMap;

    public void upLaodFiles(final List<String> fileList, int position, final IUpLoadFileListView iUpLoadFileListView) {
        if (position >= fileList.size()) {
            return;
        } else if (position == 0) {
            urlMap = new LinkedHashMap<>();
            upLoadFilecount = 0;
        }
        final String filename = fileList.get(position);
        upLoadFile(filename, new IUpLoadFileView() {
            @Override
            public void onUpLoadFileSeccuss(String url) {
                urlMap.put(url, filename);
                upLoadFilecount++;
                FileUtils.deleteFile(filename);
                if (upLoadFilecount < fileList.size()) {
                    if (iUpLoadFileListView != null) {
                        iUpLoadFileListView.onUpLoaditemSussuss(url,upLoadFilecount,fileList.size());
                    }
                    upLaodFiles(fileList, upLoadFilecount, iUpLoadFileListView);
                } else if (upLoadFilecount == fileList.size()) {
                    if (iUpLoadFileListView != null) {
                        iUpLoadFileListView.onUpLoadFileSeccuss(urlMap);
                    }
                }
            }

            @Override
            public void onUpLoadFileFail(String errormsg) {
                upLoadFilecount = 0;
                urlMap = new LinkedHashMap<>();
                if (iUpLoadFileListView != null) {
                    iUpLoadFileListView.onUpLoadFileFail("上传图片失败");
                }
            }
        });
    }

    @Override
    public void upLoadFile(final String filename, final IUpLoadFileView upLoadFileView) {
        HttpManager.getInstance().sendRequest(new GetQiniuTokenRequest(new Response.Listener<QiniuTokenResponse>() {
            @Override
            protected void onSuccess(QiniuTokenResponse response) {
                if (response != null && !TextUtils.isEmpty(response.upload_token)) {
                    upLoadFileToQiNiu(new File(filename), response.upload_token, upLoadFileView);
                } else {
                    upLoadFileView.onUpLoadFileFail("获取上传的token失败");
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                upLoadFileView.onUpLoadFileFail(exception.getErrorMessage());
            }
        }));
    }

    public void setUploadManager(UploadManager uploadManager) {
        this.uploadManager = uploadManager;
    }

    private void upLoadFileToQiNiu(File file, String token, final IUpLoadFileView upLoadFileView) {
        uploadManager.put(file, file.getName(), token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK()) {
                    Log.i("qiniu", "Upload Success");
                    upLoadFileView.onUpLoadFileSeccuss(Constants.QI_NIU_URL + key);
                } else {
                    Log.i("qiniu", "Upload Fail");
                    upLoadFileView.onUpLoadFileFail("上传头像失败");
                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                }
            }
        }, null);
    }

}
